import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

class NetworkDemo extends StatefulWidget {
  NetworkDemo({Key key}) : super(key: key);

  @override
  _NetworkDemoState createState() => _NetworkDemoState();
}

class _NetworkDemoState extends State<NetworkDemo> {

  var subscription;
  String _stateText;

  @override
  void initState() {
    super.initState();
      subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if(result == ConnectivityResult.wifi) {
        setState(() {
          _stateText = '处于Wifi';
        });
      } else if(result == ConnectivityResult.mobile) {
        setState(() {
          _stateText = '处于手机网络';
        });
      } else {
        setState(() {
          _stateText = '没有网络';
        });
      }
    });
    
  }

  @override
  dispose() {
    super.dispose();
    subscription.cancel(); //一定要销毁
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('检测网络变化') 
      ), 
      body: Center(
        child: Text(this._stateText) 
      )
    );
  }
}